<?php

class Silk_Mapi_Model_Api2_Home_Rest extends Silk_Mapi_Model_Api2_Home
{
    const HOMEPAGE_BANNER_ID = 13;

    public function _retrieve()
    {
        $flush = $this->getRequest()->getParam('flush');
        $cacheKey = 'QSLB_APP_HOME_' . Mage::app()->getStore()->getId();
        $cache = Mage::app()->getCache();
        if (!$flush) {
            if ($data = $cache->load($cacheKey))
                return json_decode($data, true);
        }

        $banners = $this->_getBanners();
        $products = $this->_getHomeProducts();
        $results = array(
            'banners' => $banners,
            'categories' => $products
        );

        $cache->save(json_encode($results), $cacheKey, array('QSLB_APP'), 3600);
        return $results;
    }

    protected function _getBanners()
    {
        date_default_timezone_set('Asia/Shanghai');
        $today = date("Y-m-d H:i:s");
        /** @var Magestore_Bannerslider_Model_Mysql4_Banner_Collection $banners */
        $storeId = Mage::app()->getStore()->getId() ?: 0;
        $banners = Mage::getModel('bannerslider/banner')->getCollection()
            ->setStoreId($storeId)
            ->addFieldToFilter('bannerslider_id', self::HOMEPAGE_BANNER_ID)
            ->addFieldToFilter('status', 0)
            ->addFieldToFilter('start_time', array('lteq' => $today))
            ->addFieldToFilter('end_time', array('gteq' => $today))
            ->setOrder('order_banner', "ASC");

        $banners->getSelect()->join(array('table_alias' => $banners->getTable('bannerslider/value')), 'main_table.banner_id = table_alias.banner_id And table_alias.store_id = '.$storeId);
        $banners->getSelect()->group("main_table.banner_id");
        $data = array();

        foreach ($banners as $banner) {
            $url = $banner->getClickUrl();
            $id = 0;
            $type = 'promotion';
            if (preg_match('/catalog\/category\/view\/id\/(\d+)(?:.*cat=(\d+))?/i', $url, $match)) {
                $type = 'category';
                if (isset($match[2]) && $match[2])
                    $id = $match[2];
                else
                    $id = $match[1];
            } elseif (preg_match('/catalog\/product\/view\/id\/(\d+)/', $url, $match)) {
                $type = 'product';
                $id = $match[1];
            }

            $data[] = array(
                'name' => $banner->getName(),
                'type' => $type,
                'image' => Mage::helper('bannerslider')->getBannerImage($banner->getImage()),
                'url_id' => (int)$id,
                'url' => $url ?: '',
            );
        }

        return $data;
    }

    protected function _getHomeProducts()
    {
        $catIds = array(14, 101, 5, 6, 8, 9, 10, 11, 13);
        $data = array();
        foreach ($catIds as $catId) {

            if ($catId == 101 && Mage::app()->getStore()->getWebsiteId() == '6') {
                $data[] = array(
                    'id' => 101,
                    'name' => '可口可乐专区',
                    'products' => $this->getCola()
                );
                continue;
            } elseif ($catId == 101) {
                continue;
            }

            $category = Mage::getModel('catalog/category')->load($catId);
            $collection = $this->_getAvailableProductCollection($category);
            $collectionSize = $collection->getSize();
            if ($collectionSize) {
                if ($collectionSize < 3)
                    continue;
                if ($collectionSize < 6)
                    $collection->setPage(1, 3);
                else
                    $collection->setPage(1, 6);
            } else
                continue;

            if ($catId == 14) {
                $data[] = array(
                    'id' => (int)$category->getId(),
                    'name' => $category->getName(),
                    'products' => $this->getExplosion()
                );
                continue;
            }

            $data[] = array(
                'id' => (int)$category->getId(),
                'name' => $category->getName(),
                'products' => $this->_formatProductCollection($collection)
            );
        }

        return $data ?: array();
    }

    protected function getCola()
    {
        $brands = array(27,51,50,324,402,52,53,499,500);
        /** @var Mage_Catalog_Model_Resource_Product_Collection $collection */
        $collection = Mage::getResourceModel('catalog/product_collection');
        $store = Mage::app()->getStore();
        $availableAttributes = array('brand', 'name', 'price', 'promotion', 'tag', 'special_price', 'special_from_date', 'special_to_date', 'small_image', 'image', 'position', 'visibility', 'status', 'promotion_image');
        $collection
            ->addWebsiteFilter($store->getWebsite())
            ->setStoreId($store->getId())
            ->addAttributeToSelect($availableAttributes)
            ->addAttributeToFilter('visibility', array(
                'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
            ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
            ->addAttributeToFilter('brand', array('in'=>$brands))
            ->setOrder('tag', 'desc');
        Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

        $collection->setPageSize(6)->setCurPage(1);
        return $this->_formatProductCollection($collection);
    }

    protected function getExplosion()
    {
        $store = Mage::app()->getStore();
        $availableAttributes = array('brand', 'name', 'price', 'promotion', 'tag', 'special_price', 'special_from_date', 'special_to_date', 'small_image', 'position', 'visibility', 'status');
        $collection = Mage::getModel('catalog/product')->getCollection()->setStoreId($store->getId())
            ->addWebsiteFilter($store->getWebsiteId())
            ->addAttributeToSelect($availableAttributes)
            ->addAttributeToFilter('tag', Silk_Qslb_Helper_Tag::EXPLOSION)
            ->addAttributeToFilter('visibility', array(
                'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
            ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
            ->setOrder('tag_position', 'desc');
        Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
        $collection->setPageSize(6)->setCurPage(1);
        return $this->_formatProductCollection($collection);
    }

    /**
     * @param Mage_Catalog_Model_Category $collection
     * @return Mage_Catalog_Model_Resource_Product_Collection $collection
     */
    protected function _getAvailableProductCollection(Mage_Catalog_Model_Category $collection)
    {
        $collection = $collection->getProductCollection();
        $store = Mage::app()->getStore();
        $availableAttributes = array('brand', 'name', 'price', 'promotion', 'tag', 'special_price', 'special_from_date', 'special_to_date', 'small_image', 'position', 'visibility', 'status');
        $collection->setStoreId($store->getId())
            ->addWebsiteFilter($store->getWebsiteId())
            ->addAttributeToSelect($availableAttributes)
            ->addAttributeToFilter('visibility', array(
                'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
            ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
            ->setOrder('position');
        Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
        $collection->getSelect()->distinct();

        return $collection;
    }

    protected function _formatProductCollection(Mage_Catalog_Model_Resource_Product_Collection $collection)
    {
        $results = array();
        $imgHelper = Mage::helper('catalog/image');
        foreach ($collection as $product) {
            /** @var Mage_Catalog_Model_Product $product */
            $product = Mage::getModel('catalog/product')->load($product->getId());
            $results[] = array(
                'id' => (int)$product->getId(),
                'name' => $product->getName(),
                'price' => (float)$product->getPrice(),
                'special_price' => (float)$product->getFinalPrice(),
                'image' => $imgHelper->init($product, 'small_image')->resize(250) . "",
                //'promotion' => $product->getPromotion() ?: '',
                'tag' => $product->getAttributeText('tag') ? (int)$product->getResource()->getAttribute('tag')->getSource()->getOptionId($product->getAttributeText('tag')) : 0
            );
        }
        return $results;
    }
}